package com.devops.admin.util;

import io.fabric8.kubernetes.client.dsl.LogWatch;
import lombok.extern.slf4j.Slf4j;

import javax.websocket.Session;
import java.io.*;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * ClassName TailLogUtil
 * Description TODO
 * Author hepingguo
 * Date 2022/4/27 11:37
 * Version 1.0
 **/
@Slf4j
public class TailLogUtil extends Thread{
    private final Session session;
    private final BufferedReader reader;
    private final LogWatch logWatch;
    private final AtomicBoolean running = new AtomicBoolean(true);

    public TailLogUtil(Session session, BufferedReader reader, LogWatch logWatch) {
        this.session = session;
        this.reader = reader;
        this.logWatch = logWatch;
    }

    @Override
    public void run() {
        String line;
        try {
            while (running.get() && (line = reader.readLine()) != null && session.isOpen()) {
                session.getBasicRemote().sendText(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            logWatch.close();
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void stopRunning() {
        running.set(false);
        logWatch.close();
    }

}
